package com.crazy.web.controller;

import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.lang.Validator;
import com.crazy.captcha.CaptchaUtils;
import com.crazy.enums.Constants;
import com.crazy.model.major.dto.UserSession;
import com.crazy.rest.RestResult;
import com.crazy.web.service.user.PermissionService;
import com.crazy.web.service.user.RegisterService;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登入相关接口
 * @author zhaochaofeng
 * @version 1.0
 * @date 2020/11/18 11:11
 */
@Log4j2
@Controller
public class LoginController extends BaseController {

    @Autowired
    private RegisterService registerService;

    /**
     * 图形验证码，用assets开头可以排除shiro拦截
     */
    @GetMapping("/assets/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        try {
            CaptchaUtils.outPng(request, response);
        } catch (IOException e) {
            log.error(Constants.ERROR, e);
        }
    }

    @ResponseBody
    @PostMapping("/doLogin")
    public RestResult login(@RequestParam String userName, @RequestParam String password,
                            @RequestParam String verificate, HttpServletRequest request) {
        if (!CaptchaUtils.ver(verificate, request)) {
            CaptchaUtils.clear(request);
            return RestResult.createFailedResult("验证码不正确");
        }
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                userName,
                password
        );
        //必须设置成true后，才会在服务器重启后，用户登录状态不丢失
        usernamePasswordToken.setRememberMe(true);
        //进行验证，这里可以捕获异常，然后返回对应信息
        subject.login(usernamePasswordToken);
        UserSession userSession = getUserSession();
        return RestResult.createSuccessResult("登录成功", userSession);
    }

    @ResponseBody
    @PostMapping("/doRegister")
    public RestResult register(@RequestParam String userName, @RequestParam String password, @RequestParam String confirmPassword) {
        Validator.validateNotEmpty(userName, "用户名不能为空");
        Validator.validateNotEmpty(password, "密码不能为空");
        Validator.validateNotEmpty(confirmPassword, "密码不能为空");
        Validator.validateEqual(password, confirmPassword, "两次密码不相同");
        registerService.register(userName, password);
        return RestResult.createSuccessResult("注册成功");
    }
}
